<template>
	<div class="statistics-table">
		<!-- 统计概览表格 -->
		<div class="overview-section">
			<div class="section-header">
				<h4>{{ overviewSubtitle }} - {{ year }}年统计概览</h4>
				<p>数据汇总统计</p>
			</div>
			<div class="table-container">
				<!-- 骨架图 -->
				<div v-if="loading" class="skeleton-container">
					<div class="skeleton-table">
						<!-- 表头骨架 -->
						<div class="skeleton-header">
							<div class="skeleton-cell skeleton-type-header"></div>
							<div v-for="month in 12" :key="month" class="skeleton-cell skeleton-month-header"></div>
						</div>
						<!-- 表格内容骨架 -->
						<div v-for="row in 4" :key="row" class="skeleton-row">
							<div class="skeleton-cell skeleton-type-cell"></div>
							<div v-for="month in 12" :key="month" class="skeleton-cell skeleton-data-cell"></div>
						</div>
					</div>
				</div>

				<!-- 实际表格 -->
				<div v-else>
					<!-- 有概览数据时显示表格 -->
					<el-table
						v-if="hasOverviewData || overviewData.length > 0"
						:data="overviewData"
						border
						size="small"
						class="overview-table"
						:header-cell-style="headerStyle"
						height="auto"
						:max-height="280"
					>
						<el-table-column prop="typeLabel" label="类型" width="120" align="left" fixed="left">
							<template #default="{ row }">
								<div class="type-cell" :class="`type-${row.type}`">
									<span class="type-label">{{ row.typeLabel }}</span>
								</div>
							</template>
						</el-table-column>

						<el-table-column v-for="month in 12" :key="month" :label="`${year}/${String(month).padStart(2, '0')}`" min-width="100" align="center">
							<template #default="{ row }">
								<div class="month-data" :class="{ 'has-data': row.monthlyData[month - 1] > 0 }">
									{{ row.monthlyData[month - 1] }}
								</div>
							</template>
						</el-table-column>
					</el-table>

					<!-- 无概览数据时的提示 -->
					<div v-else class="no-data-container overview-no-data">
						<div class="no-data-content">
							<el-empty description="暂无概览数据">
								<template #image>
									<div class="custom-empty-icon">📊</div>
								</template>
								<template #description>
									<p>当前查询条件下暂无统计概览数据</p>
								</template>
							</el-empty>
						</div>
					</div>
				</div>
			</div>
		</div>

		<!-- 部门详细统计表格 -->
		<div class="department-section" v-if="showDepartmentDetails && (hasDepartmentData || loading)">
			<div class="section-header">
				<h4>子部门统计详情</h4>
				<p>各子部门月度数据详情</p>
			</div>
			<div class="table-container">
				<!-- 骨架图 -->
				<div v-if="loading" class="skeleton-container">
					<div class="skeleton-table department-skeleton">
						<!-- 表头骨架 -->
						<div class="skeleton-header">
							<div class="skeleton-cell skeleton-dept-header"></div>
							<div class="skeleton-cell skeleton-type-header"></div>
							<div v-for="month in 12" :key="month" class="skeleton-cell skeleton-month-header small"></div>
						</div>
						<!-- 表格内容骨架 - 模拟多个部门 -->
						<div v-for="dept in 3" :key="dept" class="skeleton-dept-group">
							<div v-for="row in 4" :key="row" class="skeleton-row">
								<div v-if="row === 1" class="skeleton-cell skeleton-dept-cell"></div>
								<div v-else class="skeleton-cell skeleton-empty-cell"></div>
								<div class="skeleton-cell skeleton-type-cell"></div>
								<div v-for="month in 12" :key="month" class="skeleton-cell skeleton-data-cell small"></div>
							</div>
						</div>
					</div>
				</div>

				<!-- 实际表格 -->
				<el-table
					v-else
					:data="departmentTableData"
					border
					size="small"
					:header-cell-style="headerStyle"
					:span-method="spanMethod"
					height="100%"
					class="department-table"
				>
					<!-- 部门列 -->
					<el-table-column prop="deptName" label="部门" width="120" align="center" fixed="left">
						<template #default="{ row }">
							<div class="dept-cell" v-if="row.isFirstRow">
								{{ row.deptName }}
							</div>
						</template>
					</el-table-column>

					<!-- 类型列 -->
					<el-table-column prop="typeLabel" label="类型" width="100" align="left">
						<template #default="{ row }">
							<div class="type-cell" :class="`type-${row.type}`">
								<span class="type-label">{{ row.typeLabel }}</span>
							</div>
						</template>
					</el-table-column>

					<!-- 月份数据列 -->
					<el-table-column v-for="month in 12" :key="month" :label="`${month}月`" align="center" min-width="80">
						<template #default="{ row }">
							<div class="month-data" :class="{ 'has-data': row.monthlyData[month - 1] > 0 }">
								{{ row.monthlyData[month - 1] }}
							</div>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</div>
	</div>
</template>

<script setup lang="ts">
import { computed } from 'vue';

interface Props {
	/** 年份 */
	year: string;
	/** 统计数据 */
	statisticsData: any;
	/** 是否显示概览 */
	showOverview?: boolean;
	/** 是否显示部门详情 */
	showDepartmentDetails?: boolean;
	/** 概览副标题 */
	overviewSubtitle?: string;
	/** 加载状态 */
	loading?: boolean;
}

const props = withDefaults(defineProps<Props>(), {
	showOverview: true,
	showDepartmentDetails: true,
	overviewSubtitle: '全部部门',
	loading: false,
});

defineEmits<{
	refresh: [];
}>();

// 数据类型配置
const DATA_TYPES = [
	{ label: '已完成', value: 'completed', field: 'CompletedCount' },
	{ label: '已创建', value: 'created', field: 'CreatedCount' },
	{ label: '进行中', value: 'inprocess', field: 'InProcessCount' },
	{ label: '草稿', value: 'draft', field: 'DraftCount' },
];

// 表格头部样式
const headerStyle = {
	background: '#4a90e2',
	color: '#ffffff',
	fontWeight: '600',
	fontSize: '14px',
};

// 是否有概览数据 (MonthlyDetails)
const hasOverviewData = computed(() => {
	if (!props.statisticsData) {
		return false;
	}

	const monthly = props.statisticsData.MonthlyDetails;
	return Array.isArray(monthly) && monthly.length > 0;
});

// 是否有部门详情数据 (DepartmentDetails)
const hasDepartmentData = computed(() => {
	if (!props.statisticsData) {
		return false;
	}

	const deptData = props.statisticsData.DepartmentDetails;
	return Array.isArray(deptData) && deptData.length > 0;
});

// 是否有任何数据 (用于兼容性)
const hasData = computed(() => {
	return hasOverviewData.value || hasDepartmentData.value;
});

// 概览表格数据
const overviewData = computed(() => {
	if (!props.statisticsData) {
		return [];
	}

	// 1) 优先使用 MonthlyDetails（月度概览数据）
	const monthlyDetails = props.statisticsData.MonthlyDetails;
	if (Array.isArray(monthlyDetails) && monthlyDetails.length > 0) {
		// 按月份汇总数据
		const monthlyTotals = Array.from({ length: 12 }, () => ({
			CompletedCount: 0,
			CreatedCount: 0,
			InProcessCount: 0,
			DraftCount: 0,
		}));

		// 将月度数据填入对应月份
		monthlyDetails.forEach((monthData: any) => {
			const monthIndex = (monthData.Month || 0) - 1;
			if (monthIndex >= 0 && monthIndex < 12) {
				monthlyTotals[monthIndex].CompletedCount = monthData.CompletedCount || 0;
				monthlyTotals[monthIndex].CreatedCount = monthData.CreatedCount || 0;
				monthlyTotals[monthIndex].InProcessCount = monthData.InProcessCount || 0;
				monthlyTotals[monthIndex].DraftCount = monthData.DraftCount || 0;
			}
		});

		// 生成表格行数据
		const result = DATA_TYPES.map((dataType) => ({
			type: dataType.value,
			typeLabel: dataType.label,
			monthlyData: monthlyTotals.map((month) => month[dataType.field as keyof typeof month] || 0),
		}));

		return result;
	}

	// 2) 如果没有 MonthlyDetails，尝试从 DepartmentDetails 聚合（兼容性处理）
	const departmentDetails = props.statisticsData.DepartmentDetails;
	if (!Array.isArray(departmentDetails) || departmentDetails.length === 0) {
		return [];
	}

	// 按月份汇总数据
	const monthlyTotals = Array.from({ length: 12 }, () => ({
		CompletedCount: 0,
		CreatedCount: 0,
		InProcessCount: 0,
		DraftCount: 0,
	}));

	// 聚合所有部门的数据
	departmentDetails.forEach((dept: any) => {
		// 情况 A：部门下有 MonthlyDetails
		if (Array.isArray(dept.MonthlyDetails)) {
			dept.MonthlyDetails.forEach((monthData: any) => {
				const monthIndex = (monthData.Month || 0) - 1;
				if (monthIndex >= 0 && monthIndex < 12) {
					monthlyTotals[monthIndex].CompletedCount += monthData.CompletedCount || 0;
					monthlyTotals[monthIndex].CreatedCount += monthData.CreatedCount || 0;
					monthlyTotals[monthIndex].InProcessCount += monthData.InProcessCount || 0;
					monthlyTotals[monthIndex].DraftCount += monthData.DraftCount || 0;
				}
			});
		} else {
			// 情况 B：DepartmentDetails 是扁平的月度数据
			const monthIndex = (dept.Month || 0) - 1;
			if (monthIndex >= 0 && monthIndex < 12) {
				monthlyTotals[monthIndex].CompletedCount += dept.CompletedCount || 0;
				monthlyTotals[monthIndex].CreatedCount += dept.CreatedCount || 0;
				monthlyTotals[monthIndex].InProcessCount += dept.InProcessCount || 0;
				monthlyTotals[monthIndex].DraftCount += dept.DraftCount || 0;
			}
		}
	});

	// 生成表格行数据
	const result = DATA_TYPES.map((dataType) => ({
		type: dataType.value,
		typeLabel: dataType.label,
		monthlyData: monthlyTotals.map((month) => month[dataType.field as keyof typeof month] || 0),
	}));

	return result;
});

// 部门表格数据 - 完全按接口数据格式处理，支持全部月份数据展示
const departmentTableData = computed(() => {
	const deptDetails = props.statisticsData?.DepartmentDetails;

	if (!Array.isArray(deptDetails) || deptDetails.length === 0) {
		return [];
	}

	// 按部门分组所有月份的数据
	const deptMap = new Map();

	deptDetails.forEach((dept) => {
		if (!deptMap.has(dept.GroupId)) {
			deptMap.set(dept.GroupId, {
				groupName: dept.GroupName,
				monthlyRecords: [], // 存储该部门所有月份的数据
			});
		}

		// 如果有MonthlyDetails，将其中的数据展开作为月度记录
		if (dept.MonthlyDetails && Array.isArray(dept.MonthlyDetails)) {
			deptMap.get(dept.GroupId).monthlyRecords = dept.MonthlyDetails;
		} else {
			// 如果没有MonthlyDetails，使用原来的逻辑（兼容性处理）
			deptMap.get(dept.GroupId).monthlyRecords.push(dept);
		}
	});

	const result: any[] = [];

	// 为每个部门和每种数据类型生成表格行
	deptMap.forEach((deptInfo, deptId) => {
		DATA_TYPES.forEach((dataType, typeIndex) => {
			// 生成12个月的数据，根据接口返回的月份数据填充
			const monthlyData = Array.from({ length: 12 }, (_, index) => {
				const month = index + 1;
				// 在该部门的记录中查找对应月份的数据
				const monthRecord = deptInfo.monthlyRecords.find((record: any) => record.Month === month);

				if (monthRecord) {
					const value = monthRecord[dataType.field] || 0;
					return value;
				}
				return 0;
			});

			result.push({
				deptId,
				deptName: deptInfo.groupName,
				type: dataType.value,
				typeLabel: dataType.label,
				isFirstRow: typeIndex === 0,
				monthlyData,
			});
		});
	});

	return result;
});

// 合并单元格方法
const spanMethod = ({ row, columnIndex }: any) => {
	// 只对部门名称列（第一列）进行合并
	if (columnIndex === 0) {
		if (row.isFirstRow) {
			// 返回合并的行数（每个部门有4种类型）
			return {
				rowspan: DATA_TYPES.length,
				colspan: 1,
			};
		} else {
			// 其他行不显示
			return {
				rowspan: 0,
				colspan: 0,
			};
		}
	}

	// 其他列不合并
	return {
		rowspan: 1,
		colspan: 1,
	};
};
</script>

<style lang="scss" scoped>
.statistics-table {
	height: 100%;
	display: flex;
	flex-direction: column;
	padding: 20px;
	overflow: hidden;

	.section-header {
		padding: 12px 0;
		text-align: left;
		flex-shrink: 0;

		h4 {
			font-size: 16px;
			font-weight: 600;
			color: var(--el-text-color-primary);
			margin: 0 0 4px 0;
		}

		p {
			font-size: 13px;
			color: var(--el-text-color-regular);
			margin: 0;
		}
	}

	.overview-section {
		margin-bottom: 20px;
		flex-shrink: 0;

		.table-container {
			border-radius: 8px;
			overflow: hidden;
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

			// 暗黑模式适配
			[data-theme='dark'] & {
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
			}
		}
	}

	.department-section {
		flex: 1;
		display: flex;
		flex-direction: column;
		min-height: 0; // 允许子元素压缩

		.table-container {
			flex: 1;
			border-radius: 8px;
			overflow: hidden; // 隐藏外层滚动条
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
			height: 100%; // 填充整个可用高度
			display: flex;
			flex-direction: column;

			// 暗黑模式适配
			[data-theme='dark'] & {
				box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
			}

			// 确保表格能够正确填充并显示滚动条
			:deep(.el-table) {
				flex: 1;
				height: 100% !important;

				.el-table__body-wrapper {
					overflow-y: auto !important;
				}
			}
		}

		.dept-cell {
			font-weight: 600;
			color: var(--el-text-color-primary);
			text-align: center;
		}
	}

	.type-cell {
		.type-label {
			padding-left: 8px;
			font-weight: 600;
		}

		&.type-completed .type-label {
			color: #27ae60;

			// 暗黑模式适配 - 稍微调亮颜色
			[data-theme='dark'] & {
				color: #2ecc71;
			}
		}

		&.type-created .type-label {
			color: #3498db;

			// 暗黑模式适配 - 稍微调亮颜色
			[data-theme='dark'] & {
				color: #3498db;
			}
		}

		&.type-inprocess .type-label {
			color: #f39c12;

			// 暗黑模式适配 - 稍微调亮颜色
			[data-theme='dark'] & {
				color: #f1c40f;
			}
		}

		&.type-draft .type-label {
			color: #95a5a6;

			// 暗黑模式适配 - 稍微调亮颜色
			[data-theme='dark'] & {
				color: #bdc3c7;
			}
		}
	}

	.month-data {
		font-weight: 600;
		color: var(--el-text-color-regular);

		&.has-data {
			background: var(--el-color-primary-light-9);
			color: var(--el-color-primary);
			padding: 4px 8px;
			border-radius: 4px;

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--next-color-hover);
				color: var(--el-color-primary);
			}
		}
	}

	.empty-state {
		flex: 1;
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 40px;
		text-align: center;
	}

	// 表格样式
	:deep(.el-table) {
		font-size: 14px;
		height: 100% !important;

		.el-table__row {
			&:hover {
				background-color: var(--el-fill-color-light) !important;

				// 暗黑模式适配
				[data-theme='dark'] & {
					background-color: var(--next-color-hover) !important;
				}
			}
		}

		.el-table__cell {
			padding: 10px 8px;

			&:first-child {
				border-right: 2px solid var(--el-border-color);
				background: var(--el-fill-color-blank) !important;

				// 暗黑模式适配
				[data-theme='dark'] & {
					border-right-color: var(--next-border-color);
				}
			}
		}

		.el-table__header {
			th {
				background: #4a90e2 !important;
				color: white !important;
				font-weight: 600 !important;
				border-color: #357abd !important;
				padding: 12px 8px !important;

				.cell {
					color: white;
				}
			}
		}

		.el-table__body-wrapper {
			overflow-x: auto;
			overflow-y: auto;
			max-height: inherit; // 继承表格的最大高度设置
		}

		// 概览表格样式
		&.overview-table {
			.el-table__cell {
				padding: 8px;
			}
		}

		// 部门表格样式
		&.department-table {
			.el-table__body-wrapper {
				flex: 1;
			}
		}
	}

	// 滚动条样式（横向和纵向）
	:deep(.el-table__body-wrapper) {
		// 横向滚动条
		&::-webkit-scrollbar:horizontal {
			height: 10px;
		}

		// 纵向滚动条
		&::-webkit-scrollbar:vertical {
			width: 10px;
		}

		&::-webkit-scrollbar-track {
			background: var(--el-fill-color-light);
			border-radius: 5px;

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--el-fill-color-darker);
			}
		}

		&::-webkit-scrollbar-thumb {
			background: var(--el-color-info-light-5);
			border-radius: 5px;
			border: 1px solid var(--el-fill-color);

			&:hover {
				background: var(--el-color-info-light-3);

				// 暗黑模式适配
				[data-theme='dark'] & {
					background: var(--el-color-info-dark-2);
				}
			}

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--el-color-info-light-8);
				border-color: var(--el-fill-color-darker);
			}
		}

		// 滚动条交汇处
		&::-webkit-scrollbar-corner {
			background: var(--el-fill-color-light);

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--el-fill-color-darker);
			}
		}
	}

	// 骨架图样式
	.skeleton-container {
		width: 100%;
		overflow: hidden;
		border-radius: 8px;
		border: 1px solid var(--el-border-color);

		// 暗黑模式适配
		[data-theme='dark'] & {
			border-color: var(--next-border-color);
		}
	}

	.skeleton-table {
		width: 100%;
		min-width: 1200px; // 确保横向滚动
		background: var(--el-color-white);

		// 暗黑模式适配
		[data-theme='dark'] & {
			background: var(--next-color-disabled);
		}
	}

	.skeleton-header,
	.skeleton-row {
		display: flex;
		width: 100%;
	}

	.skeleton-header {
		background: #4a90e2;
		min-height: 44px;
		border-bottom: 1px solid #357abd;
	}

	.skeleton-row {
		min-height: 42px;
		border-bottom: 1px solid var(--el-border-color);

		&:last-child {
			border-bottom: none;
		}

		// 暗黑模式适配
		[data-theme='dark'] & {
			border-bottom-color: var(--next-border-color);
		}
	}

	.skeleton-cell {
		display: flex;
		align-items: center;
		justify-content: center;
		padding: 8px;
		border-right: 1px solid var(--el-border-color);
		position: relative;
		overflow: hidden;

		&:last-child {
			border-right: none;
		}

		// 暗黑模式适配
		[data-theme='dark'] & {
			border-right-color: var(--next-border-color);
		}

		// 骨架图动画效果
		&:before {
			content: '';
			position: absolute;
			top: 0;
			left: -100%;
			width: 100%;
			height: 100%;
			background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
			animation: skeleton-loading 1.5s infinite;

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.1), transparent);
			}
		}
	}

	// 表头骨架样式
	.skeleton-type-header {
		width: 120px;
		background: #357abd;
		border-right: 1px solid #2c5f8a;
	}

	.skeleton-dept-header {
		width: 120px;
		background: #357abd;
		border-right: 1px solid #2c5f8a;
	}

	.skeleton-month-header {
		min-width: 100px;
		background: #357abd;
		border-right: 1px solid #2c5f8a;

		&.small {
			min-width: 80px;
		}
	}

	// 表格内容骨架样式
	.skeleton-type-cell {
		width: 120px;
		background: var(--el-fill-color-light);

		// 暗黑模式适配
		[data-theme='dark'] & {
			background: var(--next-color-hover);
		}

		&:after {
			content: '';
			width: 60px;
			height: 16px;
			background: var(--el-fill-color);
			border-radius: 4px;

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--next-color-seting);
			}
		}
	}

	.skeleton-dept-cell {
		width: 120px;
		background: var(--el-fill-color-blank);

		// 暗黑模式适配
		[data-theme='dark'] & {
			background: var(--next-color-hover);
		}

		&:after {
			content: '';
			width: 50px;
			height: 16px;
			background: var(--el-fill-color);
			border-radius: 4px;

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--next-color-seting);
			}
		}
	}

	.skeleton-empty-cell {
		width: 120px;
		background: var(--el-fill-color-blank);

		// 暗黑模式适配
		[data-theme='dark'] & {
			background: var(--next-color-hover);
		}
	}

	.skeleton-data-cell {
		min-width: 100px;
		background: var(--el-fill-color);

		&.small {
			min-width: 80px;
		}

		// 暗黑模式适配
		[data-theme='dark'] & {
			background: var(--next-color-hover-rgba);
		}

		&:after {
			content: '';
			width: 30px;
			height: 14px;
			background: var(--el-fill-color-light);
			border-radius: 3px;

			// 暗黑模式适配
			[data-theme='dark'] & {
				background: var(--next-color-seting);
			}
		}
	}

	// 部门分组样式
	.skeleton-dept-group {
		&:not(:last-child) {
			border-bottom: 2px solid var(--el-border-color);

			// 暗黑模式适配
			[data-theme='dark'] & {
				border-bottom-color: var(--next-border-color);
			}
		}
	}

	// 骨架图动画
	@keyframes skeleton-loading {
		0% {
			left: -100%;
		}
		50% {
			left: 100%;
		}
		100% {
			left: 100%;
		}
	}

	// 空状态样式
	.no-data-container {
		padding: 40px 20px;
		text-align: center;
		background: var(--el-fill-color-blank);
		border-radius: 8px;
		border: 1px dashed var(--el-border-color);

		// 暗黑模式适配
		[data-theme='dark'] & {
			background: var(--next-color-hover-rgba);
			border-color: var(--next-border-color);
		}

		&.overview-no-data {
			min-height: 200px;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.no-data-content {
			.custom-empty-icon {
				font-size: 48px;
				margin-bottom: 16px;
			}

			p {
				color: var(--el-text-color-regular);
				font-size: 14px;
				margin: 8px 0 0 0;
			}
		}
	}
}
</style>
